"use client";

import React, { useEffect, useState } from "react";
import useSWR from "swr";
import { fetcher, RegionModel } from "../types";
import Link from "next/link";

// Assuming you have a Region component that displays a single region
// import Region from "../components/Region";

export default function Regions() {
    const [regions, setRegions] = useState<RegionModel[]>([]);
    const { data, error, isLoading } = useSWR<any>(`/api/region`, fetcher);

    useEffect(() => {
        if (data && data.result.data) {
            console.log(data.result.data);
            setRegions(data.result.data);
        }
    }, [data, isLoading]);

    if (error) return <div>Failed to load</div>;
    if (isLoading) return <div>Loading...</div>;
    if (!data) return null;

    const deleteRegion = async (id: number) => {
        const res = await fetch(`/api/region/${id}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            },
        });
        const content = await res.json();
        if (content.success > 0) {
            setRegions(regions?.filter((region: RegionModel) => {
                return region.id !== id;
            }));
        }
    };

    return (
        <div className="w-full max-w-7xl m-auto">
            <table className="w-full border-collapse border border-slate-400">
                <caption className="caption-top py-5 font-bold text-green-500 text-2xl">
                    List Regions - Counter :
                    <span className="text-red-500 font-bold">{regions?.length}</span>
                </caption>

                <thead>
                <tr className="text-center">
                    <th className="border border-slate-300">ID</th>
                    <th className="border border-slate-300">Name</th>
                    <th className="border border-slate-300">Parent Region</th>
                    <th className="border border-slate-300">Latitude</th>
                    <th className="border border-slate-300">Longitude</th>
                    <th className="border border-slate-300">Actions</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td colSpan={6}>
                        <Link href={`/region/create`} className="bg-green-500 p-2 inline-block text-white">Create</Link>
                    </td>
                </tr>
                {
                    regions && regions.map((region: RegionModel) => (
                        <Region key={region.id} {...region} deleteRegion={deleteRegion} />
                    ))
                }
                </tbody>
            </table>
        </div>
    );
}